package com.github.cameraxdemo;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "CameraActivity";

    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private ProcessCameraProvider cameraProvider;
    private int defaultCamera = CameraSelector.LENS_FACING_BACK;
    private Preview preview;
    private ImageCapture imageCapture;
    private PreviewView previewView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        initView();
        bindData();
    }

    private void initView() {
        previewView = findViewById(R.id.preview_view);
        ImageView switchBtn = findViewById(R.id.switch_btn_id);
        switchBtn.setOnClickListener(this);
        ImageView takeBtn = findViewById(R.id.take_btn_id);
        takeBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.switch_btn_id:
                if (defaultCamera == CameraSelector.LENS_FACING_BACK) {
                    defaultCamera = CameraSelector.LENS_FACING_FRONT;
                }
                else {
                    defaultCamera = CameraSelector.LENS_FACING_BACK;
                }
                cameraProvider.unbindAll();
                bindPreview(cameraProvider);
                break;
            case R.id.take_btn_id:
                String path = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/test.jpg";
                ImageCapture.OutputFileOptions outputFileOptions =
                        new ImageCapture.OutputFileOptions.Builder(new File(path)).build();
                imageCapture.takePicture(outputFileOptions, Executors.newSingleThreadExecutor(),
                        new ImageCapture.OnImageSavedCallback() {
                            @Override
                            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                                //Toast.makeText(CameraActivity.this, "拍照成功", Toast.LENGTH_SHORT);
                                Log.d(TAG, "拍照成功");
                            }

                            @Override
                            public void onError(@NonNull ImageCaptureException exception) {
                                //Toast.makeText(CameraActivity.this, "拍照失败", Toast.LENGTH_SHORT);
                                Log.d(TAG, "拍照失败");

                            }
                        });
        }

    }

    void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(defaultCamera)
                .build();
        preview = new Preview.Builder().build();
        preview.setSurfaceProvider(previewView.createSurfaceProvider());
        imageCapture = new ImageCapture.Builder().build();
        cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview, imageCapture);
    }

    private void bindData() {
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(new Runnable() {

            @Override
            public void run() {
                try {
                    cameraProvider = cameraProviderFuture.get();
                    bindPreview(cameraProvider);
                } catch (ExecutionException | InterruptedException e) {
                    // No errors need to be handled for this Future.
                    // This should never be reached.
                }
            }
        }, ContextCompat.getMainExecutor(this));

    }
}